package xju.rjxy.shop.web.controller;

import xju.rjxy.shop.common.framework.simplemvc.RequestMapping;
import xju.rjxy.shop.common.utils.JSONUtil;
import xju.rjxy.shop.common.utils.Result;
import xju.rjxy.shop.model.domain.Game;
import xju.rjxy.shop.model.vo.GameVO;
import xju.rjxy.shop.model.vo.HomePageVO;
import xju.rjxy.shop.service.IGameService;
import xju.rjxy.shop.service.impl.GameServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * 游戏控制层
 */
@RequestMapping("/api/game")
public class GameController {
    private final IGameService gameService = new GameServiceImpl();

    @RequestMapping("/list.do")
    public void getGameList(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] GameController.getGameList - 开始获取游戏列表");
        try {
            // TODO 条件查询列表
            System.out.println("[DEBUG] GameController.getGameList - 调用gameService.getGameList()");
            List<GameVO> gameList = gameService.getGameList();
            System.out.println("[DEBUG] GameController.getGameList - 获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            JSONUtil.printByJSON(response, Result.success(gameList));
            System.out.println("[DEBUG] GameController.getGameList - 响应发送成功");
        } catch (Exception e) {
            System.err.println("[ERROR] GameController.getGameList - 获取游戏列表失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail("获取游戏列表失败: " + e.getMessage()));
        }
    }
    
    @RequestMapping("/home.do")
    public void getHomePageData(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] GameController.getHomePageData - 开始获取首页数据");
        try {
            String userIdStr = request.getParameter("userId");
            System.out.println("[DEBUG] GameController.getHomePageData - 请求参数 userId: " + userIdStr);
            
            Integer userId = null;
            if (userIdStr != null && !userIdStr.trim().isEmpty()) {
                userId = Integer.parseInt(userIdStr);
                System.out.println("[DEBUG] GameController.getHomePageData - 解析后的userId: " + userId);
            }
            
            System.out.println("[DEBUG] GameController.getHomePageData - 调用gameService.getHomePageData()");
            HomePageVO homePageData = gameService.getHomePageData(userId);
            System.out.println("[DEBUG] GameController.getHomePageData - 获取到首页数据: " + (homePageData != null ? "成功" : "失败"));
            JSONUtil.printByJSON(response, Result.success(homePageData));
            System.out.println("[DEBUG] GameController.getHomePageData - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] GameController.getHomePageData - 用户ID格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("用户ID格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] GameController.getHomePageData - 获取首页数据失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/detail.do")
    public void getGameDetail(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] GameController.getGameDetail - 开始获取游戏详情");
        try {
            String gameIdStr = request.getParameter("gameId");
            System.out.println("[DEBUG] GameController.getGameDetail - 请求参数 gameId: " + gameIdStr);
            
            if (gameIdStr == null || gameIdStr.trim().isEmpty()) {
                System.err.println("[ERROR] GameController.getGameDetail - 游戏ID不能为空");
                JSONUtil.printByJSON(response, Result.fail("游戏ID不能为空"));
                return;
            }
            
            Integer gameId = Integer.parseInt(gameIdStr);
            System.out.println("[DEBUG] GameController.getGameDetail - 解析后的gameId: " + gameId);
            
            System.out.println("[DEBUG] GameController.getGameDetail - 调用gameService.getGameById()");
            Game game = gameService.getGameById(gameId);
            System.out.println("[DEBUG] GameController.getGameDetail - 获取到游戏详情: " + (game != null ? "成功" : "失败"));
            
            if (game == null) {
                System.err.println("[ERROR] GameController.getGameDetail - 游戏不存在，gameId: " + gameId);
                JSONUtil.printByJSON(response, Result.fail("游戏不存在"));
                return;
            }
            
            JSONUtil.printByJSON(response, Result.success(game));
            System.out.println("[DEBUG] GameController.getGameDetail - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] GameController.getGameDetail - 游戏ID格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("游戏ID格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] GameController.getGameDetail - 获取游戏详情失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/category.do")
    public void getGamesByCategory(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] GameController.getGamesByCategory - 开始按类别获取游戏");
        try {
            String category = request.getParameter("category");
            String pageStr = request.getParameter("page");
            String sizeStr = request.getParameter("size");
            
            System.out.println("[DEBUG] GameController.getGamesByCategory - 请求参数 category: " + category + ", page: " + pageStr + ", size: " + sizeStr);
            
            if (category == null || category.trim().isEmpty()) {
                System.err.println("[ERROR] GameController.getGamesByCategory - 游戏类别不能为空");
                JSONUtil.printByJSON(response, Result.fail("游戏类别不能为空"));
                return;
            }
            
            int page = pageStr != null ? Integer.parseInt(pageStr) : 1;
            int size = sizeStr != null ? Integer.parseInt(sizeStr) : 10;
            System.out.println("[DEBUG] GameController.getGamesByCategory - 解析后的参数 page: " + page + ", size: " + size);
            
            System.out.println("[DEBUG] GameController.getGamesByCategory - 调用gameService.getGamesByCategory()");
            List<GameVO> gameList = gameService.getGamesByCategory(category, page, size);
            System.out.println("[DEBUG] GameController.getGamesByCategory - 获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            JSONUtil.printByJSON(response, Result.success(gameList));
            System.out.println("[DEBUG] GameController.getGamesByCategory - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] GameController.getGamesByCategory - 分页参数格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("分页参数格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] GameController.getGamesByCategory - 按类别获取游戏失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/price.do")
    public void getGamesByPriceRange(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] GameController.getGamesByPriceRange - 开始按价格范围获取游戏");
        try {
            String minPriceStr = request.getParameter("minPrice");
            String maxPriceStr = request.getParameter("maxPrice");
            String pageStr = request.getParameter("page");
            String sizeStr = request.getParameter("size");
            
            System.out.println("[DEBUG] GameController.getGamesByPriceRange - 请求参数 minPrice: " + minPriceStr + ", maxPrice: " + maxPriceStr + ", page: " + pageStr + ", size: " + sizeStr);
            
            if (minPriceStr == null || maxPriceStr == null) {
                System.err.println("[ERROR] GameController.getGamesByPriceRange - 价格范围参数不能为空");
                JSONUtil.printByJSON(response, Result.fail("价格范围参数不能为空"));
                return;
            }
            
            Double minPrice = Double.parseDouble(minPriceStr);
            Double maxPrice = Double.parseDouble(maxPriceStr);
            int page = pageStr != null ? Integer.parseInt(pageStr) : 1;
            int size = sizeStr != null ? Integer.parseInt(sizeStr) : 10;
            System.out.println("[DEBUG] GameController.getGamesByPriceRange - 解析后的参数 minPrice: " + minPrice + ", maxPrice: " + maxPrice + ", page: " + page + ", size: " + size);
            
            System.out.println("[DEBUG] GameController.getGamesByPriceRange - 调用gameService.getGamesByPriceRange()");
            List<GameVO> gameList = gameService.getGamesByPriceRange(minPrice, maxPrice, page, size);
            System.out.println("[DEBUG] GameController.getGamesByPriceRange - 获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            JSONUtil.printByJSON(response, Result.success(gameList));
            System.out.println("[DEBUG] GameController.getGamesByPriceRange - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] GameController.getGamesByPriceRange - 参数格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("参数格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] GameController.getGamesByPriceRange - 按价格范围获取游戏失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/sales.do")
    public void getGamesBySalesOrder(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] GameController.getGamesBySalesOrder - 开始按销量排序获取游戏");
        try {
            String pageStr = request.getParameter("page");
            String sizeStr = request.getParameter("size");
            
            System.out.println("[DEBUG] GameController.getGamesBySalesOrder - 请求参数 page: " + pageStr + ", size: " + sizeStr);
            
            int page = pageStr != null ? Integer.parseInt(pageStr) : 1;
            int size = sizeStr != null ? Integer.parseInt(sizeStr) : 10;
            System.out.println("[DEBUG] GameController.getGamesBySalesOrder - 解析后的参数 page: " + page + ", size: " + size);
            
            System.out.println("[DEBUG] GameController.getGamesBySalesOrder - 调用gameService.getGamesBySalesOrder()");
            List<GameVO> gameList = gameService.getGamesBySalesOrder(page, size);
            System.out.println("[DEBUG] GameController.getGamesBySalesOrder - 获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            JSONUtil.printByJSON(response, Result.success(gameList));
            System.out.println("[DEBUG] GameController.getGamesBySalesOrder - 响应发送成功");
            
        } catch (NumberFormatException e) {
            System.err.println("[ERROR] GameController.getGamesBySalesOrder - 分页参数格式错误: " + e.getMessage());
            JSONUtil.printByJSON(response, Result.fail("分页参数格式错误"));
        } catch (Exception e) {
            System.err.println("[ERROR] GameController.getGamesBySalesOrder - 按销量排序获取游戏失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }
    
    @RequestMapping("/grouped-by-category.do")
    public void getGamesGroupedByCategory(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("[DEBUG] GameController.getGamesGroupedByCategory - 开始按类别分组获取游戏");
        try {
            System.out.println("[DEBUG] GameController.getGamesGroupedByCategory - 调用gameService.getGamesGroupedByCategory()");
            List<GameVO> gameList = gameService.getGamesGroupedByCategory();
            System.out.println("[DEBUG] GameController.getGamesGroupedByCategory - 获取到游戏列表，数量: " + (gameList != null ? gameList.size() : 0));
            JSONUtil.printByJSON(response, Result.success(gameList));
            System.out.println("[DEBUG] GameController.getGamesGroupedByCategory - 响应发送成功");
            
        } catch (Exception e) {
            System.err.println("[ERROR] GameController.getGamesGroupedByCategory - 按类别分组获取游戏失败: " + e.getMessage());
            e.printStackTrace();
            JSONUtil.printByJSON(response, Result.fail(e.getMessage()));
        }
    }

    // @RequestMapping("/grouped-by-category.do")
    // public void getGamesGroupedByCategory(HttpServletRequest request, HttpServletResponse response) {
    //     List<Game> allGames = gameService.getAllGames(); // 新增方法，查所有游戏
    //     // 按category分组
    //     Map<String, List<Game>> grouped = new LinkedHashMap<>();
    //     for (Game game : allGames) {
    //         grouped.computeIfAbsent(game.getCategory(), k -> new ArrayList<>()).add(game);
    //     }
    //     // 构造返回结构
    //     List<Map<String, Object>> result = new ArrayList<>();
    //     for (Map.Entry<String, List<Game>> entry : grouped.entrySet()) {
    //         Map<String, Object> group = new HashMap<>();
    //         group.put("category", entry.getKey());
    //         List<Map<String, Object>> games = new ArrayList<>();
    //         for (Game g : entry.getValue()) {
    //             Map<String, Object> gameMap = new HashMap<>();
    //             gameMap.put("id", g.getId());
    //             gameMap.put("game_name", g.getGameName());
    //             gameMap.put("description", g.getDescription());
    //             gameMap.put("cover", g.getPic());
    //             games.add(gameMap);
    //         }
    //         group.put("games", games);
    //         result.add(group);
    //     }
    //     JSONUtil.printByJSON(response, Result.success(result));
    // }
} 